<!--

  从零开始，使用Tauri打造一个简单的note写字板
  https://blog.csdn.net/qq285744011/article/details/149513402

-->
<template>
    <main>
        <div class="h-screen flex flex-col">
            <div class="grow-0">
                <Toolbar
                    style="border-bottom: 1px solid #ccc"
                    :editor="editorRef"
                    :defaultConfig="pd.toolbarConfig"
                    :mode="pd.mode"
                />
            </div>
            <div class="grow">
                <Editor
                    style="height: 100%; overflow-y: hidden"
                    v-model="pd.html"
                    :defaultConfig="pd.editorConfig"
                    :mode="pd.mode"
                    @onCreated="editorOnCreated"
                    @onChange="editorOnChange"
                />
            </div>
        </div>
    </main>
</template>

<style>
.w-e-text-container {
    background: linear-gradient(to bottom, #e4efe0 0%, #ffffff 90%);
}

.w-e-toolbar {
    /* background-color: transparent; */
    /* background-image: linear-gradient(181.2deg, rgb(181, 239, 249) 10.5%, rgb(254, 254, 254) 86.8%); */
    /* background: #b5eff9; */
}
</style>

<script setup>
import "@wangeditor/editor/dist/css/style.css"
import { onBeforeUnmount, ref, reactive, shallowRef, onMounted } from "vue"
import { getIdentifier, getName } from '@tauri-apps/api/app';
import { invoke, convertFileSrc } from "@tauri-apps/api/core"
import * as path from '@tauri-apps/api/path';
import { Store, load } from "@tauri-apps/plugin-store"
import { upload, download } from '@tauri-apps/plugin-upload';
import {
    exists,
    readDir,
    mkdir,
    create,
    writeFile,
    rename,
    remove,
    BaseDirectory
} from "@tauri-apps/plugin-fs"

import { Editor, Toolbar } from "@wangeditor/editor-for-vue"
import { clog } from "/src/utils/fns"

import { apiGetLastOrder, apiGetOrderList } from "/src/api/order.js"

// Store 会在 JavaScript 绑定时自动加载。
let store = null

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const pd = reactive({
    cacheFile: "tauri-cache-main.json",
    html: "",
    toolbarConfig: {},
    editorConfig: {
        placeholder: "请输入内容...",
        MENU_CONF: {
            uploadImage: {
                // 编辑器自定义上传 - https://www.wangeditor.com/v5/menu-config.html#自定义上传
                async customUpload(file, insertFn) {
                    // tauri-js写文件
                    // Tauri文件系统 写文件 https://tauri.app/zh-cn/reference/javascript/fs/#writefile
                    // tauri如何存文件到本地 https://zhuanlan.zhihu.com/p/683594936
                    // Tauri路径处理 https://v2.tauri.org.cn/plugin/file-system/#paths
                    clog(file)
                    let content = await file.arrayBuffer()
                    let ext = getImgExtByMime(file.type)
                    let fileName = String(now()) + '.' + ext
                    let localPath = await path.join(pd.imageTodayDir, fileName)
                    await writeFile(localPath, content)
                    let imgSrc = await convertFileSrc(localPath)
                    
                    // 调用 insertFn 插入图片
	                insertFn(imgSrc, fileName, imgSrc)
                },
            },
        },
    },
    mode: "default", // simple、default

    appName: '',
    identifier: '',
    baseDir: '',
    imageTodayDir: '',
    editorReady: false,
    pageExists: true,
    changed: false,
})

// https://edu.jb51.net/php/php-image-gd-image_type_to_mime_type.html
const getImgExtByMime = (mime) => {
    mime = (String(mime)).toLowerCase()
    let ext = 'jpg'
    switch (mime) {
        case 'image/png':
            ext = 'png'
            break;

        case 'image/bmp':
            ext = 'bmp'
            break;

        case 'image/psd':
            ext = 'psd'
            break;

        case 'image/tiff':
            ext = 'tiff'
            break;

        case 'image/vnd.wap.wbmp':
            ext = 'webp'
            break;

        default:
            break;
    }
    return ext
}

const editorOnCreated = (editor) => {
    editorRef.value = editor
    pd.editorReady = true
}

const editorOnChange = (e = null) => {
    // clog(e.getHtml())
    pd.html = e.getHtml()
    pd.changed = true
}

const now = () => {
    return new Date().getTime()
}
const today = () => {
    let n = new Date()
    let y = String(n.getFullYear())

    let m = n.getMonth() + 1
    if (m < 10) {
        m = '0' + String(m)
    } else {
        m = String(m)
    }

    let d = n.getDate()
    if (d < 10) {
        d = '0' + String(d)
    } else {
        d = String(d)
    }

    return y + '-' + m + '-' + d
}

const callTimer = () => {
    setTimeout(() => {
        if (pd.pageExists) {
            callTimer()
        }
    }, 1000)

    if (pd.pageExists && pd.editorReady && pd.changed) {
        goSave()
    }
}

const goSave = async () => {
    // pd.html += '<p><img src=""/></p>'

    clog(">> 已有变化")
    pd.changed = false
    await store.set("note", pd.html)
}

const dev = async () => {
    // 检查 `$APPDATA/avatar.png` 文件是否存在
    // let eee = await exists("avatar.png", { baseDir: BaseDirectory.Document })
    // clog(eee)


    // clog(pd.baseDir)
}


const initBase = async () => {
    // 初始化缓存
    store = await load(pd.cacheFile, {})

    // 初始化项目信息
    pd.identifier = await getIdentifier()
    pd.appName = await getName()

    // 初始化图片目录
    let d1 = await path.documentDir()
    let d2 = '/' + pd.appName + '/'
    let d3 = d2 + 'images/' + today() + '/'

    pd.baseDir = d2
    pd.imageTodayDir = d1 + d3
    // clog('>> imageTodayDir', pd.imageTodayDir)

    let folderExists = await exists(pd.imageTodayDir)
    if (!folderExists) {
        await mkdir(pd.imageTodayDir, { recursive: true })
    }
    
}

const initContent = async () => {
    // 尝试获取缓存
    let c = await store.get("note")
    if (typeof c == 'undefined') {
        clog(">> 建立缓存")
        await store.set("note", "")
        c = ""
    }

    // 赋值
    pd.html = c
    clog(">> 初始化内容完毕")
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
    pd.pageExists = false
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
})

onMounted(async () => {
    await initBase()
    await initContent()
    
    // 开启定时器
    callTimer()

    dev()
})
</script>
